package com.cm.creational.prototype;

import lombok.Data;

import java.util.Date;

/**
 * 原型模式很少单独出现，一般是和工厂方法模式一起出现，通过clone的方法创建一个对象，然后由工厂方法提供给调用者。
 * spring中bean的创建实际就是两种：单例模式和原型模式。（原型模式需要和工厂模式搭配起来）
 * @author cm.g
 * @date 2023/8/23 16:37
 */
@Data
public class User implements Cloneable {
    private String name;

    private Date birth;

    private int age;

    @Override
    public User clone() {
        try {
            return (User) super.clone();
        } catch (CloneNotSupportedException e) {
            throw new AssertionError();
        }
    }

    public static void main(String[] args) throws Exception {
        User user = new User();
        user.setName("cm");
        user.setBirth(new Date());
        user.setAge(18);

        User user1 = user.clone();

        System.out.println("equals:" + user1.equals(user));
        System.out.println("==:" + (user1 == user));
        speedTest();
    }

    public static void speedTest() throws Exception {
        testNew(10000);
        testClone(10000);
    }

    public static void testNew(int size) {
        long start = System.currentTimeMillis();
        for (int i = 0; i < size; i++) {
            User t = new User();
        }
        long end = System.currentTimeMillis();
        System.out.println("new的方式创建耗时：" + (end - start));
    }

    public static void testClone(int size) throws CloneNotSupportedException {
        long start = System.currentTimeMillis();
        User t = new User();
        for (int i = 0; i < size; i++) {
            User temp = (User) t.clone();
        }
        long end = System.currentTimeMillis();
        System.out.println("clone的方式创建耗时：" + (end - start));
    }
}
